package com.ruoyi.system.service.impl;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.HmzProductType;
import com.ruoyi.system.domain.HmzWarehouse;
import com.ruoyi.system.mapper.HmzWarehouseMapper;
import com.ruoyi.system.service.IHmzProductTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.HmzProductMapper;
import com.ruoyi.system.domain.HmzProduct;
import com.ruoyi.system.service.IHmzProductService;

/**
 * 用于存储产品信息的Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-10
 */
@Service
public class HmzProductServiceImpl implements IHmzProductService
{
    @Autowired
    private HmzProductMapper hmzProductMapper;
    @Autowired
    private HmzWarehouseMapper hmzWarehouseMapper;
    @Autowired
    private IHmzProductTypeService hmzProductTypeService;


    /**
     * 查询用于存储产品信息的
     *
     * @param id 用于存储产品信息的主键
     * @return 用于存储产品信息的
     */
    @Override
    public HmzProduct selectHmzProductById(Long id)
    {
        HmzProduct hmzProduct = hmzProductMapper.selectHmzProductById(id);
        if(StringUtils.isNotNull(hmzProduct)){
            HmzWarehouse hmzWarehouse = hmzWarehouseMapper.selectHmzWarehouseById(hmzProduct.getWarehouseId());
            if(StringUtils.isNotNull(hmzWarehouse)){
                hmzProduct.setWarehouseIdNmae(hmzWarehouse.getWarehouseName());
            }
        }

        return hmzProduct;
    }

    /**
     * 查询用于存储产品信息的列表
     *
     * @param hmzProduct 用于存储产品信息的
     * @return 用于存储产品信息的
     */
    @Override
    public List<HmzProduct> selectHmzProductList(HmzProduct hmzProduct)

    {
        List<HmzProduct> hmzProducts = hmzProductMapper.selectHmzProductList(hmzProduct);
        for (HmzProduct product : hmzProducts) {
            Long warehouseId = product.getWarehouseId();
            HmzWarehouse hmzWarehouse = hmzWarehouseMapper.selectHmzWarehouseById(warehouseId);
            HmzProductType hmzProductType = hmzProductTypeService.selectHmzProductTypeById(product.getProductTypeId());
            if(StringUtils.isNotNull(hmzWarehouse)){
                product.setWarehouseIdNmae(hmzWarehouse.getWarehouseName());
            }
            if(StringUtils.isNotNull(hmzProductType)){
                product.setProductTypeIdName(hmzProductType.getProductTypeName());
            }


        }
        return hmzProducts;
    }

    /**
     * 新增用于存储产品信息的
     *
     * @param hmzProduct 用于存储产品信息的
     * @return 结果
     */
    @Override
    public int insertHmzProduct(HmzProduct hmzProduct)
    {
        hmzProduct.setCreateTime(DateUtils.getNowDate());
        return hmzProductMapper.insertHmzProduct(hmzProduct);
    }

    /**
     * 修改用于存储产品信息的
     *
     * @param hmzProduct 用于存储产品信息的
     * @return 结果
     */
    @Override
    public int updateHmzProduct(HmzProduct hmzProduct)
    {
        hmzProduct.setUpdateTime(DateUtils.getNowDate());
        return hmzProductMapper.updateHmzProduct(hmzProduct);
    }

    /**
     * 批量删除用于存储产品信息的
     *
     * @param ids 需要删除的用于存储产品信息的主键
     * @return 结果
     */
    @Override
    public int deleteHmzProductByIds(Long[] ids)
    {
        return hmzProductMapper.deleteHmzProductByIds(ids);
    }

    /**
     * 删除用于存储产品信息的信息
     *
     * @param id 用于存储产品信息的主键
     * @return 结果
     */
    @Override
    public int deleteHmzProductById(Long id)
    {
        return hmzProductMapper.deleteHmzProductById(id);
    }

    @Override
    public String importUser(List<HmzProduct> stuList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(stuList) || stuList.size() == 0)
        {
            throw new ServiceException("导入基本信息数据不能为空！");
        }
        Long rfidcode= 0L;
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        List<String> list =new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String format1 = format.format(new Date());
        String s = format1.replaceAll("-", "");
        String s1 = s.replaceAll(" ", "");
        String s2 = s1.replaceAll(":", "");
        rfidcode = Long.valueOf(s2);
        for (HmzProduct stu : stuList)
        {

            try {
//                String l = String.valueOf(System.currentTimeMillis()/1000);
//                // 获取当前时间
//                LocalDateTime now = LocalDateTime.now();
//                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
//                String timestamp = now.format(formatter);
//                // rfidcode++;
////                String serialNumber = UniqueSerialNumberGenerator.generateSerialNumber();
//                String serialNumber = UniqueIdGenerator.generateUniqueId();
////                String serialNumber = UniqueIdGenerator.getTimeSerialNoStr();
//                System.err.println(serialNumber);
//                stu.setRfidCode(serialNumber);
                successNum++;
//                stu.setCreateBy(operName);
//                stu.setQuantityResidue(stu.getQuantity());
                //仓库名称
                String warehouseIdNmae = stu.getWarehouseIdNmae();
                HmzWarehouse hmzWarehouse =new HmzWarehouse();
                hmzWarehouse.setWarehouseName(warehouseIdNmae);
                List<HmzWarehouse> hmzWarehouses = hmzWarehouseMapper.selectHmzWarehouseLists(hmzWarehouse);
                if(hmzWarehouses !=null && hmzWarehouses.size()>0){
                    Long id = hmzWarehouses.get(0).getId();
                    stu.setWarehouseId(id);
                }
                String productTypeIdName = stu.getProductTypeIdName();
                HmzProductType hmzProductType = new HmzProductType();
                hmzProductType.setProductTypeName(productTypeIdName);
                List<HmzProductType> hmzProductTypes = hmzProductTypeService.selectHmzProductTypeList(hmzProductType);
                if(hmzProductTypes !=null && hmzProductTypes.size() > 0){
                    Long id = hmzProductTypes.get(0).getId();
                    stu.setProductTypeId(id);
                }
                int i = hmzProductMapper.insertHmzProduct(stu);
            } catch (Exception e) {
                failureNum++;
//                list.add(stu.getCornet());
                list.add(stu.getProductName());
                failureMsg.insert(0, list);
                throw new RuntimeException(e);
            }
//            try
//            {
//                // 验证是否存在这个用户
//                List<WmsInventory> wmsInventories = wmsInventoryMapper.selectWmsInventoryList(new WmsInventory().setRfidCode(stu.getRfidCode()));
//                if (StringUtils.isNull(u))
//                {
//                    BeanValidators.validateWithException(validator, stu);
//                    stu.setCreateBy(operName);
//                    this.insertStudentBase(stu);
//                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、学号 " + stu.getStudentNumber() + " 导入成功");
//                }
//                else if (isUpdateSupport)
//                {
//                    BeanValidators.validateWithException(validator, stu);
//                    stu.setUpdateBy(operName);
//                    this.updateStudentBase(stu);
//                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、学号 " + stu.getStudentNumber() + " 更新成功");
//                }
//                else
//                {
//                    failureNum++;
//                    failureMsg.append("<br/>" + failureNum + "、学号 " + stu.getStudentNumber() + " 已存在");
//                }
//            }
//            catch (Exception e)
//            {
//                failureNum++;
//                String msg = "<br/>" + failureNum + "、学号 " + stu.getStudentNumber() + " 导入失败：";
//                failureMsg.append(msg + e.getMessage());
//                log.error(msg, e);
//            }
        }
        if (failureNum > 0)
        {
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条");
        }
        return successMsg.toString();

    }

    @Override
    public   List<JSONObject> selectHmzProductAll() {
        List<JSONObject> lstList = new ArrayList<>();
        HmzProductType hmzProductType =new HmzProductType();
        List<HmzProductType> hmzProductTypes = hmzProductTypeService.selectHmzProductTypeList(hmzProductType);
        if(hmzProductTypes !=null && hmzProductTypes.size()>0){

            for (HmzProductType productType : hmzProductTypes) {
                JSONObject jsonObject =new JSONObject();;
                Long productTypeId = productType.getId();
                String productTypeName = productType.getProductTypeName();
                jsonObject.put("leibie",productTypeName);
                Long aLong = hmzProductMapper.selectHmzProductAllById(productTypeId);
                jsonObject.put("leibienum",aLong);
                Long aLongno = hmzProductMapper.selectHmzProductAllByIdNo(productTypeId);
                jsonObject.put("weiruku",aLongno);
                Long selectyilingyong = hmzProductMapper.selectyilingyong(productTypeId);
                jsonObject.put("yilingyong",selectyilingyong);
                Long zaiku = hmzProductMapper.selectzaiku(productTypeId);
                jsonObject.put("zaiku",zaiku);
                lstList.add(jsonObject);
            }
        }


     return lstList;
    }

    @Override
    public List<HmzProduct> selectHmzProductListNo(HmzProduct hmzProduct) {

//        List<HmzProduct> hmzProducts = hmzProductMapper.selectHmzProductList(hmzProduct);
        List<HmzProduct> hmzProducts = hmzProductMapper.selectHmzProductListNo(hmzProduct);
        for (HmzProduct product : hmzProducts) {
            Long warehouseId = product.getWarehouseId();
            HmzWarehouse hmzWarehouse = hmzWarehouseMapper.selectHmzWarehouseById(warehouseId);
            HmzProductType hmzProductType = hmzProductTypeService.selectHmzProductTypeById(product.getProductTypeId());
            if(StringUtils.isNotNull(hmzWarehouse)){
                product.setWarehouseIdNmae(hmzWarehouse.getWarehouseName());
            }
            if(StringUtils.isNotNull(hmzProductType)){
                product.setProductTypeIdName(hmzProductType.getProductTypeName());
            }


        }
        return hmzProducts;
    }
}
